import React, { useEffect, useState, useReducer, useRef } from 'react';
import styles from './index.less';
import cls from 'classnames';
import { CloseSquareOutlined, DeleteOutlined, SaveOutlined } from '@ant-design/icons';
import { InputNumber } from 'antd';
import {
  addEquipmentToProjId,
  updateEquipment,
  deleteEquipment,
} from '@/services/modelManageService';

let localKey = 1;

const DeviceInfoEdit = ({ data, onClose, onRefresh, code }) => {
  const [localData, setLocalData] = useState(null);
  // const localDataRef = useRef(null)
  const [fullDataList, setFullDataList] = useState([]);
  // const propsDataRef = useRef([])
  const [updateTable, setUpdateTable] = useState({});
  const dataRef = useRef(data);

  useEffect(() => {
    if (!localData) {
      setFullDataList(dataRef.current || []);
      return;
    }
    const _fullList = [...dataRef.current, localData];
    setFullDataList(_fullList);
  }, [localData]);

  useEffect(() => {
    setFullDataList(data);
    dataRef.current = data;
    setLocalData(null);
  }, [data]);

  function handleAddClick() {
    setLocalData({ name: '', online: 0, offline: 0, localKey: localKey++ });
  }

  function handleNumberChange(v, type, item) {
    setFullDataList(pre => {
      const next = [...pre];
      for (let i = 0; i < next.length; i++) {
        if (next[i].name === item.name) {
          next[i][type] = v;
          break;
        }
      }
      return next;
    });
    if (item.objectId) {
      setUpdateTable(pre => {
        const next = { ...pre };
        if (!next[item.name]) {
          next[item.name] = 1;
        }
        return next;
      });
    }
  }

  async function handleSubmitClick(data) {
    // requstSave()
    // onRefresh

    if (updateTable[data.name]) {
      await updateEquipment(data);

      setUpdateTable(pre => {
        const next = { ...pre };
        if (!next[data.name]) {
          next[data.name] = null;
        }
        return next;
      });
      onRefresh();
    } else if (data.localKey) {
      console.log({ code, ...data });
      await addEquipmentToProjId({ code, ...data });

      onRefresh();
    }
  }

  async function handleDeleteClick(data) {
    console.log(data);
    if (data.localKey) {
      setLocalData(null);
    } else {
      await deleteEquipment(data.objectId);
      onRefresh();
    }
  }

  function renderList() {
    return !!fullDataList.length ? (
      fullDataList.sort().reduce((result, e, i) => {
        if (!e) return result;
        result.push(
          <div key={e.localKey || e.objectId} className={styles.deviceInfoEditItem}>
            <p className={styles.deviceInfoEditItemTitle}>
              {e.localKey ? (
                <input
                  type="text"
                  value={e.name}
                  style={{ width: 120 }}
                  onChange={evt => handleNumberChange(evt.target.value, 'name', e)}
                />
              ) : (
                e.name
              )}
              <span onClick={() => handleDeleteClick(e)} className={styles.editBtn}>
                <DeleteOutlined />
                删除
              </span>
              {(e.localKey || updateTable[e.name]) && (
                <span onClick={() => handleSubmitClick(e)} className={styles.editBtn}>
                  <SaveOutlined />
                  保存
                </span>
              )}
            </p>
            <span className={styles.deviceInfoEditWorking}>
              在线{' '}
              <InputNumber
                size="small"
                min={0}
                value={e.online}
                onChange={v => handleNumberChange(v, 'online', e)}
              />
            </span>
            <span className={styles.deviceInfoEditNonWorking}>
              停工{' '}
              <InputNumber
                min={0}
                size="small"
                value={e.offline}
                onChange={v => handleNumberChange(v, 'offline', e)}
              />
            </span>
          </div>,
        );
        if (i === data.length - 1 && !localData) {
          result.push(
            <div key={'add'} className={styles.deviceInfoEditItem} onClick={handleAddClick}>
              <div className="" style={{ paddingTop: 30, textAlign: 'center', cursor: ' pointer' }}>
                <img src={require('../../images/plus-big.png')} alt="" />
              </div>
            </div>,
          );
        }
        return result;
      }, [])
    ) : (
      // <div style={{ paddingTop: 30, textAlign: 'center' }}>'暂无数据'</div>
      <div key={'add'} className={styles.deviceInfoEditItem} onClick={handleAddClick}>
        <div className="" style={{ paddingTop: 30, textAlign: 'center', cursor: ' pointer' }}>
          <img src={require('../../images/plus-big.png')} alt="" />
        </div>
      </div>
    );
  }

  return (
    <div className={cls('base-panel', styles.deviceInfoEdit)}>
      <div className="base-panel-title" style={{ paddingLeft: 12 }}>
        工区设备管理
        <span className="base-panel-title-btn" onClick={onClose}>
          <CloseSquareOutlined />
        </span>
      </div>
      <div className={cls('base-panel-body', styles.deviceInfoEditBody)}>
        <div className={cls(styles.content)}>{renderList()}</div>
      </div>
    </div>
  );
};

export default DeviceInfoEdit;
